package org.kzwl.service.web.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.entity.web.CuData;
import org.kzwl.mapper.web.CuDataMapper;
import org.kzwl.service.web.CuDataHandler;
import org.kzwl.service.web.CuDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Date;

@Service
public class CuDataServiceImpl extends ServiceImpl<CuDataMapper, CuData> implements CuDataService {


    @Override
    public CuData getToday() {
        CuData cuData = getOne(new LambdaQueryWrapper<CuData>().eq(CuData::getCuDataDate, DateUtil.beginOfDay(new Date())));
        if (cuData == null) {
            cuData = new CuData().setCuDataDate(new Date());
            this.save(cuData);
            cuData = getOne(new LambdaQueryWrapper<CuData>().eq(CuData::getCuDataDate, DateUtil.beginOfDay(new Date())));
        }
        return cuData;
    }

    @Override
    public Integer todayVisit() {
        return null;
    }

    @Override
    public synchronized void AddCount(CuData cuData) {
        CuData today = getToday();
        Field[] fields = ReflectUtil.getFields(cuData.getClass());
        for (Field field : fields) {
            if (null != ReflectUtil.getFieldValue(cuData, field)) {
                Integer value = (Integer) ReflectUtil.getFieldValue(today,field.getName());
                ReflectUtil.setFieldValue(today, field, value + 1);
                this.updateById(today);
            }
        }
    }


}
